// search.js
const app = getApp();
const musicData = require('../../utils/musicData.js');
const storage = require('../../utils/storage.js');
const api = require('../../utils/api.js');

Page({
  data: {
    keyword: '',
    searchHistory: [],
    hotKeywords: ['流行', '古风', '民谣', '治愈', '热门'],
    searchResult: [],
    isSearching: false,
    currentMusic: null,
    isPlaying: false
  },

  onLoad() {
    this.loadSearchHistory();
  },

  onShow() {
    // 更新播放状态
    this.updatePlayStatus();
  },

  // 加载搜索历史
  loadSearchHistory() {
    try {
      const history = wx.getStorageSync('searchHistory') || [];
      this.setData({ searchHistory: history.slice(0, 10) });
    } catch (e) {
      console.error('加载搜索历史失败', e);
    }
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    try {
      let history = wx.getStorageSync('searchHistory') || [];
      // 移除重复项
      history = history.filter(item => item !== keyword);
      // 添加到开头
      history.unshift(keyword);
      // 只保留10条
      history = history.slice(0, 10);
      wx.setStorageSync('searchHistory', history);
      this.setData({ searchHistory: history });
    } catch (e) {
      console.error('保存搜索历史失败', e);
    }
  },

  // 输入搜索词
  onInput(e) {
    this.setData({ keyword: e.detail.value });
  },

  // 搜索
  onSearch() {
    const keyword = this.data.keyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }
    
    this.performSearch(keyword);
    this.saveSearchHistory(keyword);
  },

  // 执行搜索（使用真实API）
  performSearch(keyword) {
    this.setData({ isSearching: true });
    
    // 调用后端搜索API
    api.searchSong(keyword).then(res => {
      console.log('搜索结果：', res);
      
      // 处理数据格式
      const searchResult = res.records.map(song => {
        // 处理音乐URL
        let musicUrl = song.url;
        if (musicUrl && !musicUrl.startsWith('http')) {
          musicUrl = api.BASE_URL + musicUrl;
        }
        
        // 处理封面URL
        let coverUrl = song.pic;
        if (coverUrl && !coverUrl.startsWith('http')) {
          coverUrl = api.BASE_URL + coverUrl;
        } else if (!coverUrl) {
          coverUrl = '/images/default-cover.jpg';
        }
        
        return {
          id: song.id,
          title: song.name,
          singer: song.singerName || '未知歌手',
          coverImgUrl: coverUrl,
          src: musicUrl, // 使用src字段
          lyric: song.lyric || ''
        };
      });
      
      this.setData({
        searchResult,
        isSearching: false
      });
      
      if (searchResult.length === 0) {
        wx.showToast({
          title: '未找到相关歌曲',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('搜索失败：', err);
      // 失败时使用本地搜索
      const result = musicData.searchMusic(keyword);
      this.setData({
        searchResult: result,
        isSearching: false
      });
    });
  },

  // 点击热门关键词
  onHotKeywordTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ keyword });
    this.performSearch(keyword);
    this.saveSearchHistory(keyword);
  },

  // 点击搜索历史
  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({ keyword });
    this.performSearch(keyword);
  },

  // 清除搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory');
          this.setData({ searchHistory: [] });
        }
      }
    });
  },

  // 播放音乐
  playMusic(e) {
    const index = e.currentTarget.dataset.index;
    const music = this.data.searchResult[index];
    
    if (!music) return;
    
    app.globalData.currentMusic = music;
    app.globalData.playlist = this.data.searchResult;
    app.globalData.playIndex = index;
    
    storage.addPlayHistory(music);
    
    const audioManager = app.globalData.audioManager;
    audioManager.title = music.title;
    audioManager.singer = music.singer;
    audioManager.coverImgUrl = music.coverImgUrl;
    audioManager.src = music.src;
    
    this.setData({
      currentMusic: music,
      isPlaying: true
    });
  },

  // 更新播放状态
  updatePlayStatus() {
    const currentMusic = app.globalData.currentMusic;
    const audioManager = app.globalData.audioManager;
    
    if (currentMusic) {
      this.setData({
        currentMusic,
        isPlaying: !audioManager.paused
      });
    }
  },

  // 切换播放/暂停
  togglePlay() {
    const audioManager = app.globalData.audioManager;
    
    if (!this.data.currentMusic) return;
    
    if (this.data.isPlaying) {
      audioManager.pause();
      this.setData({ isPlaying: false });
    } else {
      audioManager.play();
      this.setData({ isPlaying: true });
    }
  },

  // 播放下一首
  playNext() {
    const playlist = app.globalData.playlist;
    const currentIndex = app.globalData.playIndex;
    
    if (!playlist || playlist.length === 0) return;
    
    const nextIndex = (currentIndex + 1) % playlist.length;
    const nextMusic = playlist[nextIndex];
    
    app.globalData.currentMusic = nextMusic;
    app.globalData.playIndex = nextIndex;
    
    storage.addPlayHistory(nextMusic);
    
    const audioManager = app.globalData.audioManager;
    audioManager.title = nextMusic.title;
    audioManager.singer = nextMusic.singer;
    audioManager.coverImgUrl = nextMusic.coverImgUrl;
    audioManager.src = nextMusic.src;
    
    this.setData({
      currentMusic: nextMusic,
      isPlaying: true
    });
  },

  // 跳转到播放器
  goToPlayer() {
    if (this.data.currentMusic) {
      wx.navigateTo({
        url: '/pages/player/player'
      });
    }
  },

  // 清空搜索框
  clearSearch() {
    this.setData({
      keyword: ''
    });
  },

  // 重置搜索（返回初始状态）
  resetSearch() {
    this.setData({
      keyword: '',
      searchResult: [],
      isSearching: false
    });
  }
});
